package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDto dto) {
        //检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录");
        }
        //查询行为实体
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (behaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"查询实体失败");
        }
        //查询是否有该行为实体的点赞记录 如果是点赞并且有记录 提示请勿重复点赞
        //查询条件
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        //查询不喜欢行为
        ApUnlikesBehavior apUnlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        //具体行为
        int operation = dto.getType().intValue();
        //存在
        if (operation == 0 && apUnlikesBehavior != null ){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"您已设置为不喜欢");
        }
        //判断不喜欢还是取消不喜欢
        if(operation == 0){
            // 不喜欢   添加不喜欢数据
            apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setEntryId(behaviorEntry.getId());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType((short)0);
            apUnlikesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(apUnlikesBehavior);
        }else if (operation == 1){
            // 取消不喜欢  删除不喜欢数据
            mongoTemplate.remove(query,ApUnlikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}